<template>
  <div>
    <!-- 用户积分账户信息 -->
    <div class="account-container" >
      <el-card shadow="hover" class="account-card total-points">
        <div class="account-info">
          <h3>总积分</h3>
          <p>{{ accountData.totalPoints }}</p>
        </div>
      </el-card>
      <el-card shadow="hover" class="account-card available-points">
        <div class="account-info">
          <h3>可用积分</h3>
          <p>{{ accountData.availablePoints }}</p>
        </div>
      </el-card>
    </div>

    <!-- 查询与操作按钮 -->
    <div class="card" style="margin-bottom: 5px; display: flex; align-items: center;">
      <el-input v-model="searchRuleName" prefix-icon="Search" style="width: 240px; margin-right: 10px;" placeholder="请输入规则名称查询"></el-input>
      <el-button type="info" plain @click="loadTransactionsByFilters">查询</el-button>
      <el-button type="warning" plain @click="reset">重置</el-button>
    </div>

    <!-- 积分流水列表 -->
    <el-table :data="transactions" border stripe style="width: 100%;" @sort-change="handleSortChange">
      <el-table-column label="序号" width="80">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="ruleName" label="规则名称" width="150"></el-table-column>
      <el-table-column prop="points" label="变动积分" sortable="custom" width="120">
        <template #default="scope">
          <span :style="{ color: scope.row.points > 0 ? 'green' : 'red' }">{{ scope.row.points }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="balance" label="变动后余额" width="120"></el-table-column>
      <el-table-column prop="type" label="类型" width="100">
        <template #default="scope">
          {{ formatType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" sortable="custom" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 折线图 -->
    <div ref="chartRef" style="width: 100%; height: 400px;"></div>

    <!-- 分页 -->
    <div class="pagination" style="text-align: center; margin-top: 20px;">
      <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="totalItems">
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import request from '@/utils/request.js'; // 确保这是你的axios封装
import * as echarts from 'echarts';

const transactions = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);
const searchRuleName = ref('');
const sortField = ref('');
const sortOrder = ref('');
const accountData = ref({
  id: 0,
  userId: 0,
  totalPoints: 0,
  availablePoints: 0
});
const chartRef = ref(null);

// 初始化ECharts实例
let chartInstance = null;

onMounted(() => {
  chartInstance = echarts.init(chartRef.value);
  console.log('Component mounted, loading transactions and account data...');
  loadTransactions();
  getMyPoints();
});

watch(transactions, () => {
  updateChart();
});

// 加载交易记录
const loadTransactions = async (pageNum = 1, ruleName = '', sortField = '', sortOrder = '') => {
  try {
    const res = await request.get('/point/transaction/page', {
      params: {
        pageNum,
        pageSize: pageSize.value,
        ruleName,
        sortField,
        sortOrder
      }
    });
    if (res.code === '200') {
      transactions.value = res.data.list || [];
      totalItems.value = res.data.total;
      // 按照创建时间降序排序
      transactions.value.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    }
  } catch (error) {
    console.error('Failed to load transactions:', error);
  }
};

// 根据过滤条件加载交易记录
const loadTransactionsByFilters = () => {
  currentPage.value = 1; // 重置当前页为第一页
  loadTransactions(1, searchRuleName.value, sortField.value, sortOrder.value);
};

// 重置搜索条件
const reset = () => {
  searchRuleName.value = '';
  sortField.value = '';
  sortOrder.value = '';
  loadTransactions();
};

// 处理分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  loadTransactions(newPage, searchRuleName.value, sortField.value, sortOrder.value);
};

// 处理排序变化
const handleSortChange = ({ column, prop, order }) => {
  sortField.value = prop;
  sortOrder.value = order === 'ascending' ? 'asc' : 'desc';
  loadTransactions(currentPage.value, searchRuleName.value, sortField.value, sortOrder.value);
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化类型
const formatType = (type) => {
  switch (type) {
    case 1:
      return '赚取';
    case 2:
      return '消费';
    default:
      return '未知';
  }
};

// 获取个人积分账户信息
const getMyPoints = async () => {
  try {
    const res = await request.get('/point/account/myPoints');
    if (res.code === '200') {
      accountData.value = res.data;
    }
  } catch (error) {
    console.error('Failed to get my points:', error);
  }
};

// 更新ECharts图表
const updateChart = () => {
  const dates = transactions.value.map(tx => formatDate(tx.createdAt)).reverse(); // 反转日期数组
  const points = transactions.value.map(tx => tx.balance).reverse(); // 反转积分数组

  const option = {
    title: {
      text: '积分变化趋势'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: dates
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '积分',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: points
      }
    ]
  };

  chartInstance.setOption(option);
};
</script>

<style scoped>
.account-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.account-card {
  width: 48%;
  padding: 20px;
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.account-card h3 {
  font-size: 1.5em;
  margin-bottom: 15px;
  color: white;
}

.account-card p {
  font-size: 2em;
  font-weight: bold;
  color: white;
}

.total-points {
  background-color: #409EFF; /* 蓝色 */
}

.available-points {
  background-color: #67C23A; /* 绿色 */
}

.card {
  background-color: #f9fafc;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  text-align: center;
  margin-top: 20px;
}
</style>



